import axios from "../../utils/axios";
interface IOptions {
  modulePath: string;
}

const useRequest = <Request>({ modulePath }: IOptions): Request => {
  const files = require.context(`../../api`, true, /\.ts$/);
  const request: any = {};
  const key = files.keys().find((key) => key === `./${modulePath}.ts`);
  if (!key) {
    throw `找不到${modulePath}`;
  }
  if (key) {
    const module = files(key).default;
    Object.keys(module).forEach((methods) => {
      Object.keys(module[methods]).forEach((key) => {
        if (methods === "postUrl") {
          request[key] = (params?: any) =>
            axios.post(module.postUrl[key], params);
        } else if (methods === "getUrl") {
          request[key] = (params?: any) =>
            axios.get(module.getUrl[key], { params });
        } else if (methods === "putUrl") {
          request[key] = (params?: any) =>
            axios.put(module.putUrl[key], params);
        } else if (methods === "delUrl") {
          request[key] = (params?: any) =>
            axios.delete(`${module.delUrl[key]}/${params}`);
        }
      });
    });
  }
  return request;
};

export default useRequest;
